class WebSocketClient {
  constructor() {
    this.ws = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.listeners = new Map();
    this.token = null;
    this.projectId = null;
  }

  connect(projectId, token) {
    if (!projectId || !token) {
      console.error('WebSocket连接失败: projectId 和 token 是必需的');
      return;
    }

    this.token = token;
    this.projectId = projectId;

    const host = import.meta.env.VITE_WS_BASE_URL;
    try {
      const wsUrl = `${host}/ws?token=${token}&projectId=${projectId}`;
      console.log('正在连接WebSocket:', wsUrl);
      
      this.ws = new WebSocket(wsUrl);

      this.ws.onopen = () => {
        console.log('WebSocket连接成功');
        this.reconnectAttempts = 0;
        if (this.listeners.has('reconnect')) {
          this.listeners.get('reconnect').forEach(callback => callback());
        }
      };

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          console.log('收到WebSocket消息:', data);
          if (this.listeners.has(data.type)) {
            this.listeners.get(data.type).forEach(callback => callback(data.data));
          }
        } catch (error) {
          console.error('处理WebSocket消息失败:', error);
        }
      };

      this.ws.onclose = (event) => {
        console.log('WebSocket连接关闭:', event);
        if (this.listeners.has('disconnect')) {
          this.listeners.get('disconnect').forEach(callback => callback());
        }
        
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          const delay = 1000 * Math.pow(2, this.reconnectAttempts);
          console.log(`将在 ${delay/1000} 秒后尝试重新连接...`);
          
          setTimeout(() => {
            this.reconnectAttempts++;
            console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            this.connect(this.projectId, this.token);
          }, delay);
        }
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        if (this.listeners.has('error')) {
          this.listeners.get('error').forEach(callback => callback(error));
        }
      };
    } catch (error) {
      console.error('创建WebSocket连接失败:', error);
    }
  }

  on(type, callback) {
    if (!this.listeners.has(type)) {
      this.listeners.set(type, new Set());
    }
    this.listeners.get(type).add(callback);
  }

  off(type, callback) {
    if (this.listeners.has(type)) {
      this.listeners.get(type).delete(callback);
    }
  }

  disconnect() {
    if (this.ws) {
      console.log('关闭WebSocket连接');
      this.ws.close();
      this.ws = null;
    }
    this.token = null;
    this.projectId = null;
    this.listeners.clear();
    this.reconnectAttempts = 0;
  }

  reconnect() {
    if (this.token && this.projectId) {
      this.connect(this.projectId, this.token);
    } else {
      console.error('重连失败: 缺少认证信息');
    }
  }
}

export const wsClient = new WebSocketClient(); 